package me.cxlr.qinlauncher2.dao;

import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import io.realm.Realm;
import me.cxlr.qinlauncher2.model.Action;
import me.cxlr.qinlauncher2.model.App;

/**
 * ActionDao
 *
 * @author 酷安用户:山轮纸
 */
public class ActionDao {
    private Realm realm;

    /**
     * 保存
     *
     * @param actionList 启动器提供的动作
     */
    public void saveAction(ArrayList<Action> actionList) {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        realm.beginTransaction();
        List<Action> tmpList = realm.copyToRealm(actionList);
        realm.commitTransaction();
        realm.close();
    }

    /**
     * 保存
     *
     * @param action 启动器提供的动作
     */
    public void saveAction(Action action) {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        realm.beginTransaction();
        Action tmp = realm.copyToRealm(action);
        realm.commitTransaction();
        realm.close();
    }

    /**
     * 根据动作名称查询动作
     *
     * @param actionName 动作名称
     * @return Action
     */
    public Action findActionByActionName(String actionName) {
        try {
            realm = Realm.getInstance(RealmConfig.getRealmConfig());
            Action results = realm.where(Action.class)
                    .equalTo("actionName", actionName)
                    .findFirst();
            assert results != null;
            Action tmp = realm.copyFromRealm(results);
            realm.close();
            return tmp;
        } catch (Exception e) {
            Logger.e("findActionByActionName:" + e.toString());
            return null;
        }
    }

    /**
     * 查询全部动作
     *
     * @return 全部Action
     */
    public List<Action> findAllAction() {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        List<Action> results = realm.where(Action.class).findAll();
        assert results != null;
        List<Action> tmp = realm.copyFromRealm(results);
        realm.close();
        return tmp;
    }

    /**
     * 根据id查询
     *
     * @param id 主键
     * @return Action
     */
    public Action findActionById(String id) {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        Action results = realm.where(Action.class)
                .equalTo("id",id)
                .findFirst();
        assert results != null;
        Action tmp = realm.copyFromRealm(results);
        realm.close();
        return tmp;
    }
}
